/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.vng.cookies;

import com.vng.zing.lib.Config;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author kienpd
 */
public class CookieUtils {
     private static final Logger log = LoggerFactory.getLogger(CookieUtils.class);
    private static final int EXPIRED_COOKIE = 2592000; // 1 month
    private static final String format = "EEE, dd-MMM-yyyy HH:mm:ss zzz";
    private static final SimpleDateFormat formatter = new SimpleDateFormat(format);

    private static final String VNGAUTH = "vngauth";
    private static final String ZAUTH = "ZAUTH";

    /**
     * get value of specific cookie
     * @param request   httpservletrequest object
     * @param name  name of specifc cookie
     * @param defaultValue  value to return in case cookie not exist
     * @return  value of specific cookie, or defaultValue in case cookie not exist
     */
    public static String getCookie( HttpServletRequest request, String name, String defaultValue ) {
        try {
            Map<String, String> validCookies = getCookieMap(request);
//            log.debug("validCookies: {}", validCookies);

            if( validCookies == null || validCookies.isEmpty() ) {
                return defaultValue;
            } else {
                String cookie = validCookies.get(name.trim().toLowerCase());
                if( cookie == null ) {
                    return defaultValue;
                } else {
                    return cookie;
                }
            }
        } catch ( UnsupportedEncodingException ex ) {
            log.info("CookieUtils.getCookie() - Unable to decode UTF-8 cookie value");
        }

        return defaultValue;
    }

    /**
     * delete specific cookie
     * @param response httpservletresponse object
     * @param request   httpservletrequest object
     * @return httpservletresponse object with specific cookie deleted
     */
    public static HttpServletResponse removeCookie( HttpServletResponse response, HttpServletRequest request ) {
        Cookie[] cookies = request.getCookies();
        String domain = Config.getParam("setting", "domain");
        String cookieName = "";

        response.setHeader("P3P", "CP=\"NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM\"");

        for( Cookie cookie: cookies ) {
            cookieName = cookie.getName();
            if( cookieName.equals(VNGAUTH) || cookieName.equals(ZAUTH) ) {
                String headerValue = cookieName + "=deleted;Path=/;Domain=" + domain + ";Expires=Thu, 01 Jan 1970 00:00:01 GMT";
                response.setHeader("Set-Cookie", headerValue);
            }
        }

        return response;
    }

    /**
     * set specific cookie to extend 1 month
     * @param response  httpservletresponse object
     * @param domain    domain to set cookie
     * @param cookieName    name of cookie to be set
     * @param cookieValue   value of cookie to be set
     * @return  httpservletresponse object
     */
    public static HttpServletResponse setCookie( HttpServletResponse response, String domain,
            String cookieName, String cookieValue ) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, EXPIRED_COOKIE);
        String headerValue = cookieName + "=" + cookieValue + ";Path=/;Domain=" + domain + ";Expires=" + formatter.format(cal.getTime());
        response.setHeader("P3P", "CP=\"NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM\"");
        response.setHeader("Vary", "Accept-Encoding");
        response.addHeader("Set-Cookie", headerValue);
        return response;
    }

    /**
     * get all valid cookies
     * @param request   httpservletrequest object
     * @return a map contain all valid cookies
     * @throws UnsupportedEncodingException
     */
    private static Map<String, String> getCookieMap( HttpServletRequest request ) throws
            UnsupportedEncodingException {
        Map<String, String> validCookies = new HashMap<String, String>();
        Cookie[] cookies = request.getCookies();

        if( cookies != null ) {
            for( Cookie cookie: cookies ) {
                String name = cookie.getName().toLowerCase().trim();
                String value = URLDecoder.decode(cookie.getValue(), "UTF-8");

                if( !(value.equalsIgnoreCase("deleted")) ) {
                    validCookies.put(name, value);
                }
            }
        }

        return validCookies;
    }
    
}
